package com.bailiban.manager.filter;

import com.bailiban.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zhulang
 * @Classname MyFilter
 * @Description MyFilter
 */
@Component
public class MyFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        //设置白名单，对于指定请求直接放行
        String path = request.getURI().getPath();
        if (path.indexOf("/admin/login") > 0) {
            return chain.filter(exchange);
        }
        if (!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            if (!StringUtils.isEmpty(token)) {
                Claims claims = jwtUtil.parseJWT(token);
                if (claims != null && claims.get("roles").equals("admin")) {
                    System.out.println("认证通过放行");
                    return chain.filter(exchange);
                }
            }
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 0; //数值越小，优先级越高
    }
}
